package day9;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.junit.Test;

public class ExceptionDemo {
	@Test
	public void test1() {
		Student student = null;
		System.out.println(student);
		// unll.属性 null.方法
//		System.out.println(student.getName());// NullPointerException 空指针异常
		
		String str = "Hello";
//		System.out.println(str.charAt(5));// StringIndexOutofBoundsException 字符串下标越界异常
		
		int j = 3;
//		System.out.println(j / 0);// ArithmeticException 算数异常
		
		student = new Student();
		Person person = new Person();
		// java.lang.ClassCastException: day9.Person cannot be cast to day9.Student
		student = (Student) person;
		int[] array = {2, 6, 5, 59, 48, 78};// ArrayIndexOutofBoundsException
		for (int i = 0; i <=array.length; i++) {
			System.out.println(array[i]);
		}
	}
	
	@Test
	public void test2() {
		// Unhandled exception type FileNotFoundException
		// 编译时异常：写代码的时候就会抛出的异常，如果不处理就会报错
		try { // try里面包含的是"可能"会抛出的异常代码
			try {
				FileInputStream fileInputStream = new FileInputStream("a.txt");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//		catch (FileNotFoundException e) {// 如果代码抛出异常就会执行catch里面的代码
//			e.printStackTrace();
//		} 
	finally {
			// 一定会被执行的代码（不管异常抛不抛出都会执行）
			// 关闭连接、释放资源
		}
		// 即使抛出了异常，catch里面会捕获，程序不会崩溃，后面的可以继续执行
		System.out.println("----------------");
	}
	
	@Test
	public void test3() {
		FileInputStream fileInputStream;
		try {
			fileInputStream = new FileInputStream("a.txt");
			fileInputStream.read();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void test4() {
		try {
			handleException();// 谁调用谁解决
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public void handleException() throws FileNotFoundException {
		FileInputStream fileInputStream = new FileInputStream("a.txt");
	}
	
	@Test
	public void test5() {
		AccountManager accountManager = new AccountManager(1000.0);
		try {
			accountManager.withdraw(1200.0);
		} catch (MeiQianException e) {
			e.printStackTrace();
		}
	}
}
